/*
 * Copyright (c) 2014, S.F. Express Inc. All rights reserved.
 */
package org.jasig.cas.client.ext;

import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.KeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述：
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID   DATE            PERSON          REASON
 *  1    2017年11月7日     014767          Create
 * ****************************************************************************
 * </pre>
 * 
 * @author 014767
 * @since 1.0
 */
public class EncryptUtils {

    private static final Logger logger = LoggerFactory.getLogger(EncryptUtils.class);
    private static final byte[] publicKeyData = { 48, -127, -97, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3,
            -127, -115, 0, 48, -127, -119, 2, -127, -127, 0, -125, 27, 40, -6, 62, 95, -116, 118, 25, 33, 73, -32, -13, -109, 26,
            -73, -116, -48, -19, -67, 120, -14, 3, 52, 125, -85, -127, -88, -66, -9, -120, 114, -58, -59, -57, 53, 107, -36, -1,
            -91, -18, -77, 19, 82, 35, -33, -78, -24, 102, -128, 68, -23, -88, 12, 51, 95, -90, 42, 66, -59, -89, 58, -10, -79,
            -123, -53, 21, 28, -106, -22, -58, -78, -101, 20, 8, -89, -9, -61, -50, 37, 55, -82, -100, 36, -58, -72, 12, -58,
            -61, 81, -95, 57, 84, -21, 89, 94, -104, 56, -28, -27, 45, 39, -91, 3, 89, -95, 111, 88, -46, 24, -33, 71, 119, 86,
            22, -28, 113, -68, -119, -58, 74, 29, 74, 14, -116, 96, -25, -101, 2, 3, 1, 0, 1 };
    private static final String TRANSFORMATION = "RSA/None/NoPadding";
    private static final BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    private static PublicKey publicKey;

    static {
        try {
            KeySpec keySpec = new X509EncodedKeySpec(publicKeyData);
            publicKey = KeyFactory.getInstance("RSA").generatePublic(keySpec);
        } catch (Exception e) {
            logger.warn("init publicKey error", e);
        }
    }

    public static String encode(String s) {
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION, bouncyCastleProvider);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] data = cipher.doFinal(s.getBytes());
            return URLEncoder.encode(Base64.encodeBase64String(data), "UTF8");
        } catch (Exception e) {
            logger.warn("encode error: " + s, e);
            return s;
        }
    }
}
